<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">

        <el-col :span="8">
          <el-form-item label="业务员" prop="personId">
            <el-select v-model="formData.personId" placeholder="请选择业务员" filterable :disabled="formData.isDisabled" >
              <el-option
                v-for="item in personList" :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="部门" prop="deptId">
            <el-select v-model="formData.personId" placeholder="请选择部门" filterable :disabled="true">
              <el-option
                v-for="item in personList" 
                :key="item.id"
                :label="item.deptName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="订单日期" prop="orderDate" :disabled="formData.isDisabled">
            <el-date-picker
              v-model="formData.orderDate"
              type="date"
              value-format="x"
              placeholder="选择订单日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="客户" prop="customerId">
            <el-input v-model="formData.customerName" placeholder="请选择客户" @click="openDialog()" :disabled="formData.isDisabled"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" :disabled="formData.isDisabled"/>
          </el-form-item>
        </el-col>
          <el-col :span="8">
        <el-form-item label="流水号" prop="serialNumber">
        <el-input v-model="formData.serialNumber" placeholder="自动生成" :disabled="true"/>
      </el-form-item>
      </el-col>
      </el-row>

    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="销售订单" name="saleDetail">
        <SaleDetailForm ref="saleDetailFormRef" :pid="formData.id" :isDisabled="formData.isDisabled"/>
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <el-button @click="submitForm" type="primary" :disabled="formData.isDisabled" >确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>

  <customerForm ref="formRefAdd" @successCustomer="handleSuccessCustomer" />

</template>
<script setup lang="ts">
/*业务员查询*/
import {PersonApi}  from '@/api/wms/person'
/*客户数据查询*/
import {CustomerApi}  from '@/api/wms/customer'

import {SaleOrderApi, SaleOrderVO} from '@/api/wms/saleorder'
import SaleDetailForm from './components/SaleDetailForm.vue'
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import videojs from "video.js";
import log = videojs.log;
import { StringDecoder } from 'string_decoder';
import { useTagsViewStore } from '@/store/modules/tagsView'
import customerForm from './../pomain/components/CustomerForm.vue';
import { defaultProps, handleTree } from '@/utils/tree';
import { getSimpleDeptList } from '@/api/system/dept';
/** 销售订单主 表单 */
defineOptions({name: 'saleOrderFormCreate'})
const { push, currentRoute } = useRouter()

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref<string>('') // 表单的类型：create - 新增；update - 修改
const route = useRoute()
const router = useRouter()
// 业务员数据列表
const personList = ref([])
const deptList = ref<Tree[]>([]) // 树形结构
// 客户数据列表
const customerList = ref([])

// 表单数据
const formData = ref({
  id: undefined,
  serialNumber: undefined,
  personId: undefined,
  customerId: undefined,
  orderDate: new Date().getTime(),
  remark: undefined,
  isDisabled:false,
  customerName: undefined,
  deptId: 0
})
const formRules = reactive({
  personId: [{required: true, message: '业务员不能为空', trigger: 'change'}],
  customerId: [{required: true, message: '客户不能为空', trigger: 'change'}],
  orderDate: [{required: true, message: '订单日期不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('saleDetail')
const saleDetailFormRef = ref()


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await saleDetailFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'saleDetail'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SaleOrderVO
    // 拼接子表的数据
    data.saleDetails = saleDetailFormRef.value.getData()
    if (formType.value === 'create') {
      await SaleOrderApi.createSaleOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await SaleOrderApi.updateSaleOrder(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    delView(unref(currentRoute))
    push('/sale/sale-order');
    // push('/order/saleOrderIndex');

  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serialNumber: undefined,
    personId: undefined,
    customerId: undefined,
    orderDate: new Date().getTime(),
    remark: undefined,
  }
  formRef.value?.resetFields()
}

onMounted(async ()=> {
  // 通过 route.params 获取传递的参数
  const { id, type } = route.query;
  // 业务员查询
  const persons = await PersonApi.getPersonSimpleList();
  personList.value = persons
  // 查询客户
  const customers = await CustomerApi.getCustomerList();
  customerList.value = customers

  // 操作类型
  formType.value = type
  initFormData(route.query.id ? String(route.query.id) : undefined);

})

/** 初始化表单数据 */
const initFormData = async (id?: any) => {
  if (id) {  
    formLoading.value = true;
    try {
        formData.value = await SaleOrderApi.getSaleOrder(id);
      if(route.query.type=='select')
      {
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }else if(route.query.type=='update'){
        formData.value.isDisabled = false; // 修改时可以编辑
      formType.value = 'update';
      }else if(route.query.type=='create'){
      // formData.value.isDisabled = false; // 新增时可以编辑
      formType.value = 'create';
      resetForm();
      }else{
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }

      console.log()
    } finally {
      formLoading.value = false;
    }
  } else {
    // formData.value.isDisabled = false; // 创建时可以编辑
    formType.value = 'create';
  }
};


/** 返回上一页 */
const goBack = () => {
  delView(unref(currentRoute))
    push('/sale/sale-order');
}



const formRefAdd = ref(null); // 确保变量名唯一

const openDialog = () => {
  // 打开弹窗的逻辑
  formRefAdd.value.open(event);
};


const handleSuccessCustomer = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);

  formData.value.customerId = getFormData.customerId
  formData.value.customerName = getFormData.customerName

};




</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>
